package com.zzh.zzhaiagent.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import com.zzh.zzhaiagent.domain.vo.UserProfilesVO;
import com.zzh.zzhaiagent.utils.JwtUtil;
import com.zzh.zzhaiagent.utils.RedisHutoolHashUtil;
import com.zzh.zzhaiagent.utils.RequestHeaderUtils;
import com.zzh.zzhaiagent.utils.WebFrameworkUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import static com.zzh.zzhaiagent.constant.RedisKeyConstant.USER_INFO_KEY_PREFIX;

/**
 * @author: zzh
 * @date: 2025/05/30 10:43:13
 * @version: 1.0
 */
//需要对请求头进行token验证 filter再最前面
@Component
@Slf4j
public class TokenAuthenticationFilter implements HandlerInterceptor {

    @Resource
    private RedisHutoolHashUtil redisHutoolHashUtil;

    /**
     * 请求预处理
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //从请求中获取token
        String token = RequestHeaderUtils.getAuthorization(request);
        if (StrUtil.isBlank(token)){
            log.error("token is null");
            return false;
        }
        //校验token是否过期
        if (JwtUtil.isTokenExpired(token)){
            response.setStatus(401);//401状态标识过期，前端捕获到401进行处理刷新token
            return false;//token过期
        }
        //token有效，解析token获取用户信息，存储到ThreadLocal中
        Claims claims = JwtUtil.parseJWT(token);
        if (claims == null){
            log.error("token is invalid");
            response.setStatus(401);//401状态标识过期，前端捕获到401进行处理刷新token
            return false;
        }
        String userId = claims.getSubject();
        //可以从userId中获取用户信息,数据库查询/redis缓存获取
        UserProfilesVO userProfiles = redisHutoolHashUtil.getUserProfiles(USER_INFO_KEY_PREFIX + userId);
        if (userProfiles == null){
            log.error("user is not exist");
            return false;
        }
        WebFrameworkUtils.setLoginUserId(request,userId);//存储用户id到request中 后续可以使用获取用户信息
        WebFrameworkUtils.setUserInfo(request,userProfiles);//存储用户信息到request中 后续可以使用获取用户信息
        return true;//放行
    }


    /**
     * 请求拦截器执行完回调方法
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        WebFrameworkUtils.removeLoginUserId(request);
        WebFrameworkUtils.removeUserInfo(request);
    }


}
